package com.controller;
import com.domain.BlogArticle;
import com.domain.Statistic;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.BlogArticleMapper;
import com.mapper.StatisticMapper;
import com.utils.Commons;
import org.hibernate.stat.Statistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.List;
@Controller
public class IndexController {
   @Autowired
    BlogArticleMapper blogArticleMapper;
   @Autowired
    StatisticMapper statisticMapper;
   @Autowired
    Commons commons;
   public  List<BlogArticle> getHeatArticles() {
       List<Statistic> list = statisticMapper.getStatistic();
       List<BlogArticle> articlelist = new ArrayList<>();
       for (int i = 0; i < list.size(); i++) {
           BlogArticle article = blogArticleMapper.selectArticleWithId(list.get(i).getArticleId());
           article.setHits(list.get(i).getHits());
           article.setCommentsNum(list.get(i).getCommentsNum());
           articlelist.add(article);
           if (i >= 9) {
               break;
           }
       }
       return articlelist;
   }
   public PageInfo<BlogArticle> selectArticleWithPage(Integer page,Integer count){
       PageHelper.startPage(page,count);
       List<BlogArticle> articleList=blogArticleMapper.selectArticleWithPage();
       for (int i=0;i<articleList.size();i++){
           BlogArticle article=articleList.get(i);
           Statistic statistic=statisticMapper.selectStatisticWithArticle(article.getId());
           article.setHits(statistic.getHits());
           article.setCommentsNum(statistic.getCommentsNum());
       }
       PageInfo<BlogArticle> pageInfo=new PageInfo<>(articleList);
       return pageInfo;
   }
   @GetMapping(value = "/")
    private String index(Model model) { return this.index(model, 1, 5);}
    @GetMapping(value = "/page/{p}")
    public String index(Model model,@PathVariable("p") int page,@RequestParam(value = "count",defaultValue = "5")int count){
       PageHelper.startPage(page,count);
       PageInfo<BlogArticle> articles=selectArticleWithPage(page,count);
       List<BlogArticle> articleList=getHeatArticles();
       model.addAttribute("articles",articles);
       model.addAttribute("articleList",articleList);
       return "client/index1";

    }

}
